package online.config;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Auther: 狼芒
 * @Date: 2021/10/3 16:47
 * @Descrintion: 整合Shiro
 * @version: 1.0
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro的内置过滤器
        /*
          anon:无需认证就能访问
          authc: 必须认证才能访问
          user：必须拥有记住我才能访问
          perms: 拥有对某个资源的权限才能访问
          role： 拥有某个角色才能访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
//        filterMap.put("shiro/*", "anno");
        filterMap.put("/shiro/authc", "authc");
//        filterMap.put("/shiro/login", "authc");
        filterMap.put("/shiro/user", "user");
        filterMap.put("/shiro/perms", "perms[user:add]");
//        filterMap.put("shiro/role", "role");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录跳转
        bean.setLoginUrl("login");
        //设置未授权页面
        bean.setUnauthorizedUrl("401");
        return bean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 创建Realm对象，需要自定义类
     */
    @Bean(name = "userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }


    /**
     * 权限认证
     * 需要开启Shiro AOP注解支持
     * @RequiresPermissions({"userinfo:view"})
     * @RequiresRoles({"wangjing"})等注解的支持
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
